package mo.leetcode_top;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class L341_NestedIterator implements Iterator<Integer> {

    private List<Integer> list = new ArrayList<>();
    private int i = 0;

    public L341_NestedIterator(List<NestedInteger> nestedList) {
        for (NestedInteger nestInteger : nestedList) {
            handleIterator(nestInteger);
        }
    }

    @Override
    public Integer next() {
        if (list.size() == 0) {
            return null;
        }
        return list.get(i++);
    }

    @Override
    public boolean hasNext() {
        return i < list.size();
    }

    private void handleIterator(NestedInteger nestedInteger) {
        if (nestedInteger.isInteger()) {
            list.add(nestedInteger.getInteger());
        } else {
            for (NestedInteger ele : nestedInteger.getList()) {
                handleIterator(ele);
            }
        }
    }

    private interface NestedInteger {


        public boolean isInteger();

        public Integer getInteger();

        public List<NestedInteger> getList();

    }
}
